// ============================================
// 13 - 生命周期 (Lifetimes)
// ============================================

/// 生命周期是 Rust 最独特的特性之一
/// 确保引用在需要时始终有效

// ==================== 生命周期基础 ====================

/// 生命周期防止悬垂引用
pub fn lifetime_basics() {
    println!("\n=== 生命周期基础 ===");
    
    let r;
    {
        let x = 5;
        // r = &x; // ❌ 错误: x 的生命周期太短
        r = 5; // ✅ 正确: 直接赋值
    }
    
    println!("r: {}", r);
    
    println!("\n生命周期确保引用始终有效");
}

/// 借用检查器
pub fn borrow_checker() {
    println!("\n=== 借用检查器 ===");
    
    let x = 5;            // ----------+-- 'a
    let r = &x;           // --+-- 'b  |
    println!("r: {}", r); //   |       |
                          // --+       |
                          // ----------+
    
    println!("借用检查器比较作用域确保所有借用都有效");
}

// ==================== 函数中的生命周期 ====================

/// 需要生命周期注解的函数
pub fn lifetime_annotation_syntax() {
    println!("\n=== 生命周期注解语法 ===");
    
    let string1 = String::from("长字符串");
    let string2 = "xyz";
    
    let result = longest(string1.as_str(), string2);
    println!("最长的字符串是: {}", result);
}

// 生命周期注解语法
// 'a 读作 "生命周期 a"
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

/// 生命周期注解的含义
pub fn lifetime_annotation_meaning() {
    println!("\n=== 生命周期注解含义 ===");
    
    println!("生命周期注解:");
    println!("1. 不改变引用的生命周期");
    println!("2. 描述多个引用生命周期之间的关系");
    println!("3. 允许借用检查器拒绝无效引用");
}

/// 深入理解生命周期
pub fn understanding_lifetimes() {
    println!("\n=== 深入理解生命周期 ===");
    
    let string1 = String::from("长字符串在这里");
    
    {
        let string2 = String::from("xyz");
        let result = longest(string1.as_str(), string2.as_str());
        println!("最长的字符串是: {}", result);
    }
    
    // 这个例子可以工作，因为 result 的使用在 string2 的作用域内
}

/// 生命周期注解实例
pub fn lifetime_example() {
    println!("\n=== 生命周期示例 ===");
    
    let string1 = String::from("长字符串在这里");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
        println!("内部作用域: {}", result); // ✅ 可以
    }
    // println!("{}", result); // ❌ 错误: string2 已被释放
}

// ==================== 结构体中的生命周期 ====================

/// 结构体定义中的生命周期注解
#[derive(Debug)]
struct ImportantExcerpt<'a> {
    part: &'a str,
}

pub fn lifetime_in_struct() {
    println!("\n=== 结构体中的生命周期 ===");
    
    let novel = String::from("叫我以实玛利。多年以前...");
    let first_sentence = novel.split('.').next().expect("找不到 '.'");
    
    let excerpt = ImportantExcerpt {
        part: first_sentence,
    };
    
    println!("摘录: {:?}", excerpt);
}

// ==================== 生命周期省略规则 ====================

/// 生命周期省略规则
pub fn lifetime_elision() {
    println!("\n=== 生命周期省略 ===");
    
    // 这个函数不需要生命周期注解
    fn first_word(s: &str) -> &str {
        let bytes = s.as_bytes();
        
        for (i, &item) in bytes.iter().enumerate() {
            if item == b' ' {
                return &s[0..i];
            }
        }
        
        &s[..]
    }
    
    let s = "hello world";
    let word = first_word(s);
    println!("第一个单词: {}", word);
    
    println!("\n生命周期省略规则:");
    println!("1. 每个引用参数都有自己的生命周期");
    println!("2. 如果只有一个输入生命周期，赋给所有输出");
    println!("3. 如果有 &self 或 &mut self，self 的生命周期赋给所有输出");
}

// ==================== 方法中的生命周期 ====================

/// 方法定义中的生命周期注解
impl<'a> ImportantExcerpt<'a> {
    // 根据省略规则，不需要注解
    fn level(&self) -> i32 {
        3
    }
    
    // 根据规则三，返回值的生命周期与 self 相同
    fn announce_and_return_part(&self, announcement: &str) -> &str {
        println!("请注意: {}", announcement);
        self.part
    }
}

pub fn lifetime_in_methods() {
    println!("\n=== 方法中的生命周期 ===");
    
    let novel = String::from("叫我以实玛利。多年以前...");
    let first_sentence = novel.split('.').next().expect("找不到 '.'");
    let excerpt = ImportantExcerpt {
        part: first_sentence,
    };
    
    println!("级别: {}", excerpt.level());
    println!("部分: {}", excerpt.announce_and_return_part("重要消息"));
}

// ==================== 静态生命周期 ====================

/// 'static 生命周期
pub fn static_lifetime() {
    println!("\n=== 静态生命周期 ===");
    
    // 字符串字面量有 'static 生命周期
    let s: &'static str = "我有静态生命周期";
    println!("{}", s);
    
    println!("\n'static 表示引用可以在整个程序期间存活");
    println!("所有字符串字面量都是 'static");
}

// ==================== 泛型、Trait Bound 和生命周期 ====================

/// 结合泛型、trait bound 和生命周期
pub fn generic_trait_lifetime() {
    println!("\n=== 泛型 + Trait + 生命周期 ===");
    
    fn longest_with_announcement<'a, T>(
        x: &'a str,
        y: &'a str,
        ann: T,
    ) -> &'a str
    where
        T: std::fmt::Display,
    {
        println!("公告! {}", ann);
        if x.len() > y.len() {
            x
        } else {
            y
        }
    }
    
    let string1 = String::from("xyz");
    let string2 = "abc";
    
    let result = longest_with_announcement(
        string1.as_str(),
        string2,
        "今天是新的一天",
    );
    
    println!("最长的字符串是: {}", result);
}

// ==================== 多个生命周期参数 ====================

/// 使用多个生命周期参数
pub fn multiple_lifetimes() {
    println!("\n=== 多个生命周期参数 ===");
    
    fn longest_with_multiple<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
        // 返回值的生命周期只与 x 相关
        x
    }
    
    let string1 = String::from("长字符串");
    {
        let string2 = String::from("短");
        let result = longest_with_multiple(string1.as_str(), string2.as_str());
        println!("结果: {}", result);
    }
}

// ==================== 生命周期约束 ====================

/// 生命周期约束
pub fn lifetime_bounds() {
    println!("\n=== 生命周期约束 ===");
    
    struct Ref<'a, T: 'a> {
        reference: &'a T,
    }
    
    let x = 5;
    let _r = Ref { reference: &x };
    
    println!("生命周期约束 T: 'a 表示 T 的任何引用必须至少与 'a 一样长");
}

// ==================== 实际应用示例 ====================

/// 字符串解析器
#[derive(Debug)]
struct Parser<'a> {
    input: &'a str,
    position: usize,
}

impl<'a> Parser<'a> {
    fn new(input: &'a str) -> Self {
        Parser { input, position: 0 }
    }
    
    fn parse_word(&mut self) -> Option<&'a str> {
        let start = self.position;
        let bytes = self.input.as_bytes();
        
        while self.position < bytes.len() && bytes[self.position] != b' ' {
            self.position += 1;
        }
        
        if start == self.position {
            return None;
        }
        
        let word = &self.input[start..self.position];
        self.position += 1; // 跳过空格
        Some(word)
    }
}

pub fn practical_parser() {
    println!("\n=== 实际应用: 解析器 ===");
    
    let input = "hello rust world";
    let mut parser = Parser::new(input);
    
    while let Some(word) = parser.parse_word() {
        println!("解析到单词: {}", word);
    }
}

/// 配置结构体
#[derive(Debug)]
struct Config<'a> {
    name: &'a str,
    value: &'a str,
}

impl<'a> Config<'a> {
    fn new(name: &'a str, value: &'a str) -> Self {
        Config { name, value }
    }
    
    fn display(&self) {
        println!("{} = {}", self.name, self.value);
    }
}

pub fn practical_config() {
    println!("\n=== 实际应用: 配置 ===");
    
    let name = "port";
    let value = "8080";
    
    let config = Config::new(name, value);
    config.display();
}

/// 迭代器包装
struct StrSplit<'a> {
    remainder: &'a str,
    delimiter: &'a str,
}

impl<'a> StrSplit<'a> {
    fn new(haystack: &'a str, delimiter: &'a str) -> Self {
        StrSplit {
            remainder: haystack,
            delimiter,
        }
    }
}

impl<'a> Iterator for StrSplit<'a> {
    type Item = &'a str;
    
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(next_delim) = self.remainder.find(self.delimiter) {
            let until_delimiter = &self.remainder[..next_delim];
            self.remainder = &self.remainder[next_delim + self.delimiter.len()..];
            Some(until_delimiter)
        } else if self.remainder.is_empty() {
            None
        } else {
            let rest = self.remainder;
            self.remainder = "";
            Some(rest)
        }
    }
}

pub fn practical_iterator() {
    println!("\n=== 实际应用: 字符串分割迭代器 ===");
    
    let haystack = "a,b,c,d,e";
    let letters: Vec<_> = StrSplit::new(haystack, ",").collect();
    println!("分割结果: {:?}", letters);
}

// ==================== 生命周期最佳实践 ====================

/// 生命周期使用最佳实践
pub fn best_practices() {
    println!("\n=== 生命周期最佳实践 ===");
    
    println!("1. 优先依赖生命周期省略规则");
    println!("2. 只在必要时添加生命周期注解");
    println!("3. 使用有意义的生命周期参数名");
    println!("4. 理解借用检查器的工作原理");
    println!("5. 避免返回不必要的引用");
    println!("6. 考虑使用所有权转移代替借用");
    println!("7. 'static 生命周期要谨慎使用");
}

/// 常见生命周期错误
pub fn common_mistakes() {
    println!("\n=== 常见生命周期错误 ===");
    
    println!("1. 返回指向局部变量的引用");
    println!("2. 在不同作用域混淆生命周期");
    println!("3. 过度使用 'static");
    println!("4. 不理解生命周期省略规则");
    println!("5. 在结构体中存储引用时忘记生命周期");
}

/// 主函数 - 演示所有功能
#[allow(dead_code)]
pub fn main() {
    println!("╔════════════════════════════════════════╗");
    println!("║   Rust 生命周期教程                    ║");
    println!("╚════════════════════════════════════════╝");
    
    lifetime_basics();
    borrow_checker();
    lifetime_annotation_syntax();
    lifetime_annotation_meaning();
    understanding_lifetimes();
    lifetime_example();
    lifetime_in_struct();
    lifetime_elision();
    lifetime_in_methods();
    static_lifetime();
    generic_trait_lifetime();
    multiple_lifetimes();
    lifetime_bounds();
    practical_parser();
    practical_config();
    practical_iterator();
    best_practices();
    common_mistakes();
    
    println!("\n✅ 生命周期教程完成！");
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_longest() {
        let string1 = String::from("long");
        let string2 = "xyz";
        let result = longest(string1.as_str(), string2);
        assert_eq!(result, "long");
    }
    
    #[test]
    fn test_important_excerpt() {
        let novel = String::from("Call me Ishmael. Some years ago...");
        let first_sentence = novel.split('.').next().expect("Could not find a '.'");
        let excerpt = ImportantExcerpt {
            part: first_sentence,
        };
        assert_eq!(excerpt.part, "Call me Ishmael");
    }
    
    #[test]
    fn test_str_split() {
        let haystack = "a,b,c";
        let letters: Vec<_> = StrSplit::new(haystack, ",").collect();
        assert_eq!(letters, vec!["a", "b", "c"]);
    }
}

